import { inject, observer } from 'mobx-react';

import { Tabs, Button, Tag, message } from 'antd';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
import {
  WeaTab,
  WeaSearchGroup,
  WeaFormItem,
  WeaDropdown,
  WeaTag,
  WeaLocaleProvider,
} from 'ecCom';
import InnerHref from '../../util/InnerHref';
import CoworkConstant from '../../util/CoworkConstant';
import { createSortMenu, createMarkMenu } from '../../util/CoworkUtil';

const TabPane = Tabs.TabPane;
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;

const CustomComp = ({ render, type, record, func, children, ...rest }) => {
  const onHandleClick = () => func(record);
  const onHandleClose = () => func(rest.str, record);

  if (render) {
    return React.cloneElement(render, {
      onClose: onHandleClose,
      children,
    });
  }
  switch (type) {
    case 'a':
      return (
        <a {...rest} onClick={onHandleClick}>
          {children}
        </a>
      );
    case 'span':
      return <span {...rest} onClick={onHandleClick} />;
    default:
      return null;
  }
};

@inject('coworkMainStore')
@observer
class CoworkTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showSearchAd: false,
      tabKey: 'all',
    };
  }

  componentDidMount() {
    const { coworkMainStore } = this.props;
    const { getCoworkLabelList } = coworkMainStore;
    // 获取标签设置列表
    getCoworkLabelList();
  }

  render() {
    const { coworkMainStore } = this.props;
    const { config, comsWeaTableStore, formJoinType } = coworkMainStore;
    const { params, form } = coworkMainStore.leftList;
    // 按标签
    const labelL = config.labelList;
    const labelList = labelL;
    let topTab = [
      { title: getLabel(332, '全部'), key: 'all' },
      { title: getLabel(25426, '未读'), key: 'unread' },
      { title: getLabel(382626, '标星'), key: 'important' },
      { title: getLabel(16636, '隐藏'), key: 'hidden' },
    ];
    labelList.length > 0 &&
      labelList
        .filter(label => label.isUsed == 1)
        .map((label) => {
          topTab.push({ title: label.labelName, key: label.id });
        });
    let selectedKeys = params.type;
    if (
      ['all', 'unread', 'important', 'hidden'].every(
        key => key != selectedKeys,
      )
    ) {
      selectedKeys = params.labelid;
    }
    let { name } = form.getFormParams();
    return (
      <div className="wea-cowork-listview">
        <WeaTab
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTab@e32lvb`}
          datas={topTab}
          searchType={['base', 'advanced']}
          showSearchAd={this.state.showSearchAd}
          searchsAd={this.getSearchs(this.state.tabKey)}
          setShowSearchAd={this.setShowSearchAd}
          hideSearchAd={this.hideSearchAd}
          buttonsAd={this.getTabButtonsAd()}
          keyParam="key"
          selectedKey={selectedKeys}
          onChange={this.changeTabKey}
          searchsBaseValue={name}
          onSearchChange={this.changeSearchInput}
          onSearch={this.search}
          leftStyle={{ paddingRight: 350 }}
        />
        <div className="mid-area">
          <Tabs
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Tabs@76qdg8`}
            type="card"
            className="listview-filter"
            onChange={this.changeThemeKey}
            activeKey={formJoinType}
          >
            {CoworkConstant.themeMenu().map(item => (
              <TabPane
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_TabPane@kacsxe@${item.key}`}
                tab={item.label}
                key={item.key}
              />
            ))}
          </Tabs>
          <div className="extraContent">
            {createSortMenu(params.orderType, this.changeSortKey)}
            <WeaDropdown
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaDropdown@ax1g3o`}
              overlay={createMarkMenu(labelList, this.mark)}
            >
              {getLabel(81293, '标记为')}...
            </WeaDropdown>
          </div>
        </div>
        <WeaTable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTable@oroxln`}
          className="listview-list"
          comsWeaTableStore={comsWeaTableStore}
          needScroll={true}
          getColumns={this.getNewColumns}
        />
      </div>
    );
  }

  setShowSearchAd = bool => this.setState({ showSearchAd: bool });
  hideSearchAd = () => this.setState({ showSearchAd: false });
  // 高级搜索group定义
  getSearchs(tabKey) {
    const { coworkMainStore } = this.props;
    const { condition, form } = coworkMainStore.leftList;
    let group = [];
    form.isFormInit &&
      condition.map((c) => {
        let items = [];
        c.items.map((fields) => {
          if (fields.domkey[0] == 'ishide' && tabKey === 'hidden') {
            return;
          }
          if (fields.domkey[0] == 'viewType' && tabKey === 'unread') {
            return;
          }
          if (fields.domkey[0] == 'star' && tabKey === 'important') {
            return;
          }
          items.push({
            com: (
              <WeaFormItem
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaFormItem@updoo1@${fields.domkey[0]}`}
                label={`${fields.label}`}
                labelCol={{ span: `${fields.labelcol}` }}
                wrapperCol={{ span: `${fields.fieldcol}` }}
                viewAttr={fields.viewAttr}
              >
                <WeaSwitch
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaSwitch@efj12c@${fields.domkey[0]}`}
                  fieldConfig={fields}
                  form={form}
                  onEnterSearch={this.search}
                  onChange={this.onFormChange}
                />
              </WeaFormItem>
            ),
            colSpan: 1,
          });
        });
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@10nioj@group}`}
            needTigger={true}
            title={c.title}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  }

  onFormChange = (res, obj) => {
    const { coworkMainStore } = this.props;
    if (res && Object.keys(res)[0] === 'jointype') {
      coworkMainStore.setStoreState({
        formJoinType: obj.value,
      });
    }
  };

  // 定义tab中点击高级搜索时的最下面的操作按钮集合
  getTabButtonsAd() {
    return [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@4orqlr@search`}
        type="primary"
        onClick={this.search}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@hq63pd@reset`}
        type="ghost"
        onClick={this.reset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@8urodb@cancel`}
        type="ghost"
        onClick={this.cancelSearch}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
  }

  // 改变页签选中状态并根据条件筛选
  changeTabKey = (tableKey) => {
    const { coworkMainStore } = this.props;
    let params = {};
    let { setParams, getLeftList, config } = coworkMainStore;
    const label = config.labelList;
    let sign = {};
    label.map((lab) => {
      if (tableKey == lab.id) {
        return (sign = lab);
      }
    });
    switch (tableKey) {
      case 'all':
        params = { type: 'all', labelid: 'allTab', layout: 2 };
        break;
      case 'unread':
        params = { type: 'unread', labelid: '1', layout: 2 };
        break;
      case 'important':
        params = { type: 'important', labelid: '2', layout: 2 };
        break;
      case 'hidden':
        params = { type: 'hidden', labelid: '3', layout: 2 };
        break;
      case sign.id:
        params = { type: sign.labelType, labelid: sign.id, layout: 2 };
        break;
    }
    this.state.tabKey = tableKey;
    setParams(params);
    getLeftList();
  };

  // 根据主题条件筛选
  changeThemeKey = (key) => {
    const { coworkMainStore } = this.props,
      { form } = coworkMainStore.leftList;
    let { getLeftList, setStoreState } = coworkMainStore;
    form.updateFields({
      jointype: {
        value: key,
      },
    });
    setStoreState({ formJoinType: key });
    getLeftList();
    coworkMainStore.changeJoinType({ joinType: key });
  };

  // 取消高级搜索
  cancelSearch = () => {
    this.setState({
      showSearchAd: false,
    });
  };

  // 改变排序方式
  changeSortKey = (key) => {
    const {
      coworkMainStore: { setParams, getLeftList },
    } = this.props;
    setParams({ orderType: key });
    getLeftList();
  };

  // 获取高级搜索条件
  search = () => {
    const {
      coworkMainStore: {
        setParams,
        getLeftList,
        formJoinType,
        leftList,
        setStoreState,
      },
    } = this.props;
    const { jointype } = leftList && leftList.form.getFormParams();
    if (jointype !== formJoinType) {
      setStoreState({ formJoinType: jointype });
    }
    setParams({ layout: 2 });
    getLeftList();
    this.setState({
      showSearchAd: false,
    });
  };

  // 标记为
  mark = (item) => {
    const { coworkMainStore } = this.props,
      { comsWeaTableStore } = coworkMainStore;
    if (item.key == 'tag') {
      coworkMainStore.getCoworkLabelList();
      coworkMainStore.setTagVisible(true);
      return;
    }
    let checkIds = comsWeaTableStore.selectedRowKeys;
    if (!checkIds || checkIds.length == 0) {
      message.info(getLabel(4902, '请选择要标记的协作', 'note'));
      return;
    }
    let ids = checkIds.join();
    if (item.key >= 0) {
      coworkMainStore.markItemAsType({
        coworkids: ids,
        type: 'addLabel',
        labelIds: item.key,
      });
      coworkMainStore.getLeftList();
    } else {
      coworkMainStore.markItemAsType({ coworkids: ids, type: item.key });
      // coworkMainStore.getLeftList();
    }
  };

  onHandleMarkTable = (record) => {
    const { coworkMainStore } = this.props;
    window.open(InnerHref.coworkSingleHref(record.id));
    coworkMainStore.markTable([record.id], 'read');
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      if (column.dataIndex == 'name') {
        column.render = (text, record) => {
          let strs =
            record.id_strspan != undefined && JSON.parse(record.id_strspan);
          return (
            <div className="cowork-list-name">
              {record.approvalAtatus == '1' && (
                <span className="cowork-approval">
                  【{getLabel(2242, '待审批')}】
                </span>
              )}
              <CustomComp
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_CustomComp@rwuuwg@${record.id}`}
                type={'a'}
                record={record}
                style={record.isnew == 1 ? { fontWeight: 600 } : null}
                func={this.onHandleMarkTable}
              >
                {text}
              </CustomComp>
              {record.isTop == '1' && (
                <Tag
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Tag@epikdj`}
                  className="cowork-top"
                >
                  Top
                </Tag>
              )}
              <div style={{ display: 'block' }}>
                {strs.length > 0 &&
                  strs.map((str, index) => (
                    <CustomComp
                      ecId={`${
                        (this && this.props && this.props.ecId) || ''
                      }_CustomComp@728bje@${record.id}_${index}`}
                      render={
                        <WeaTag
                          ecId={`${
                            (this && this.props && this.props.ecId) || ''
                          }_WeaTag@qgabwd@${index}`}
                          className="listview-tag"
                          color={str.labelColor}
                          closable
                          title={str.labelName}
                        />
                      }
                      str={str}
                      record={record}
                      func={this.deleteTag}
                    >
                      {str.labelName}
                    </CustomComp>
                  ))}
              </div>
            </div>
          );
        };
      } else if (column.dataIndex == 'important') {
        column.render = (text, record) => {
          if (record.important == '0') {
            return (
              <CustomComp
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_CustomComp@pvsos4`}
                type="span"
                className="icon-coms-Collection cursor-pointer"
                style={{ fontSize: '15px', color: '#f6a623' }}
                func={this.markSingle}
                record={record}
              />
            );
          } else if (record.important == '1') {
            return (
              <CustomComp
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_CustomComp@jgbss3`}
                type="span"
                record={record}
                className="icon-coms-Collection2 cursor-pointer"
                style={{ fontSize: '15px', color: '#f6a623' }}
                func={this.markSingle}
              />
            );
          }
        };
      }
      return column;
    });
    return newColumns;
  };
  markSingle = (record) => {
    const { coworkMainStore } = this.props;
    if (record.important === '0') {
      coworkMainStore.markItemAsType({
        coworkids: record.id,
        type: 'important',
      });
    } else if (record.important === '1') {
      coworkMainStore.markItemAsType({ coworkids: record.id, type: 'normal' });
    }
  };

  deleteTag = (label, record) => {
    const { coworkMainStore } = this.props;
    coworkMainStore.deleteCoworkLabels(label, record.id);
  };

  changeSearchInput = (value) => {
    const { coworkMainStore } = this.props,
      { form } = coworkMainStore.leftList;
    form.updateFields({
      name: {
        value,
      },
    });
  };

  reset = () => {
    const { form } = this.props.coworkMainStore.leftList;
    form.resetConditionValue();
  };
}

export default CoworkTable;
